package rsj.service.usage.org;

import com.alibaba.fastjson.JSON;
import com.rlyy.aibase.utils.base.TableNode;
import common.util.QueryRunnerFactory;
import rsj.api.org.entity.CurrentTableColumn;
import rsj.api.org.entity.UsageReportParam;
import rsj.service.usage.ICalculateUsage;

import java.sql.Connection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 查询机构模块-产品使用量
 *
 * @author yuanqinglong
 * @since 2021/3/12 15:21
 */
public interface IOrgCalculateUsage extends ICalculateUsage {


    /**
     * 机构模块-查询接口的使用量分组累计
     *
     * @param statisticColumnEntities 查询列表的数据 不包含使用量
     * @param connection              数据库连接
     * @param statEnv                 环境（01：测试环境，02：生产环境，03：线下测试环境）
     * @param usageReportParam        请求参数
     */
    @Override
    default void queryInterfaceUsageThroughContract(List<CurrentTableColumn> statisticColumnEntities, Connection connection, String statEnv, UsageReportParam usageReportParam) {
        List<String> prodUid = statisticColumnEntities.stream().map(CurrentTableColumn::getStatProdUid).distinct().collect(Collectors.toList());
        List<String> orgpId = statisticColumnEntities.stream().map(CurrentTableColumn::getStatOrgpId).distinct().collect(Collectors.toList());
        String orgpIdValues = ICalculateUsage.assemblyInQueryConditions(orgpId);
        String prodUidValues = ICalculateUsage.assemblyInQueryConditions(prodUid);
        String sql = "SELECT stat_orgp_id,stat_useamount,stat_prod_uid FROM sys.sys_stat " +
                " WHERE stat_env = '" + statEnv + "' AND stat_org_id = '" + usageReportParam.getStatOrgId() + "' AND stat_orgp_id IN (" + orgpIdValues + ") " +
                " AND stat_prod_uid IN (" + prodUidValues + ")";
        TableNode tableNode = QueryRunnerFactory.getQueryRunner().queryLinkTableNode(connection, sql);
        List<CurrentTableColumn> tableColumns = JSON.parseArray(tableNode.toJson(), CurrentTableColumn.class);
        // 计算使用量和剩余量
        this.fillInTheRemainingUsageField(statisticColumnEntities, tableColumns, usageReportParam);
    }



    /**
     * 填写剩余使用量字段
     *  @param statisticColumnEntities 产品使用情况列字段（不包含剩余量字段）需通过tableColumns进行计算
     * @param tableColumns            包含剩余量的集合
     * @param usageReportParam        请求参数
     */
    @Override
    default void fillInTheRemainingUsageField(List<CurrentTableColumn> statisticColumnEntities, List<CurrentTableColumn> tableColumns, UsageReportParam usageReportParam) {
        Map<String, List<CurrentTableColumn>> groupStatisticsUsage = tableColumns.stream().collect(Collectors.groupingBy(currentTableColumn -> currentTableColumn.getStatOrgpId() + currentTableColumn.getStatProdUid()));
        Map<String, String> groupingAndAdding = new LinkedHashMap<>();
        groupStatisticsUsage.forEach((key, currentTableColumns) -> {
            // 分组后 每组的接口使用量对应累加
            Map<Integer, Integer> groupStatistics = new LinkedHashMap<>();
            // 这个组有多条使用量、将每条的对应接口使用量想加 得出一个总的使用量
            // 例：key下有List<A,B> 两个元素
            // ：A 元素字段statUseamount 接口使用量 10,10,10,10
            // ：B 元素字段statUseamount 接口使用量 20,20,20,20
            // 最终统计为groupingAndAdding-> key : (A.statUseamount + B.statUseamount = 30,30,30,30)
            currentTableColumns.forEach(currentTableColumn -> {
                // 如果合同是组合包量 数组是多个元素
                String[] useMountArray = currentTableColumn.getStatUseamount().split(",");
                List<Integer> useList = Stream.of(useMountArray).map(Integer::parseInt).collect(Collectors.toList());
                for (int i = 0; i < useList.size(); i++) {
                    groupStatistics.put(i, useList.get(i) + groupStatistics.getOrDefault(i, 0));
                }
            });
            groupingAndAdding.put(key, groupStatistics.values().stream().map(String::valueOf).collect(Collectors.joining(",")));
        });
        // 将每条产品使用情况的使用量赋值
        statisticColumnEntities.forEach(currentTableColumn -> {
            String statUseMount = groupingAndAdding.get(currentTableColumn.getStatOrgpId() + currentTableColumn.getStatProdUid());
            currentTableColumn.setStatUseamount(statUseMount);
        });

        // 如果需要、计算剩余量
        this.ifYouNeedToCalculateTheRemainingAmount(statisticColumnEntities);
    }
}
